<?php
	require_once dirname(BASEPATH) . '/application/models/local/data/cafe/_init_model_cafe.php';
	
	class mod_cafe_expire extends _init_model_cafe
	{
		public $CAF_E_ID;
		public $CAF_ID;
		public $CAF_E_S_DATE;
		public $CAF_E_E_DATE;
		public $CAF_E_DAY_REMAIN;
		public $PAK_ID;
		
		function mod_cafe_expire(){
			parent::__construct();
			
			$this->tableName = "cafe_expire";				
		}
		
		function get_current_package_state($cafe_id, $load_config=false, $show_default=false){
			
			if ($load_config)
				$data = array('CAF_E_S_DATE','CAF_E_E_DATE',
								'package.PAK_ID','package.PAK_NAME',
								'package_config.*');
			else
				$data = array('CAF_E_S_DATE','CAF_E_E_DATE',
									'package.PAK_ID','package.PAK_NAME');
			
			$this->db->select($data);
			$this->db->where('CAF_ID', $cafe_id);
			$this->db->join('package', 'package.PAK_ID = cafe_expire.PAK_ID');
			
			if ($load_config)
				$this->db->join('package_config', 'package_config.PAK_ID = cafe_expire.PAK_ID');
			
			$query = $this->db->get($this->tableName);
			
			if ($query->num_rows() > 0){
				$row = $query->row_array(0);
				
				$this->load->library('custom_datetime');				
				$row['DAY_REMAIN'] = $this->custom_datetime->date_diff($this->custom_datetime->current_date(), $row['CAF_E_E_DATE']);
				
				// check if package state is null then add default package
				if (empty($row['PAK_ID']) || $row['PAK_ID'] == 1){
					$this->load->model('local/data/mod_package');
					$package = $this->mod_package->get_free_package_detail();
					$row['PAK_ID'] = $package['PAK_ID'];
					$row['PAK_NAME'] = $package['PAK_NAME'];
					$row['DAY_REMAIN'] = 'INF';
				}
				
				return $row;
			} else {
				// show default value
				if ($show_default){
					$this->load->model('local/data/mod_package');
					$package = $this->mod_package->get_free_package_detail();
					
					$package['DAY_REMAIN'] =  'INF';
					$package['CAF_E_S_DATE'] = '-';
					$package['CAF_E_E_DATE'] = '-';
					return $package;
				} else
					return null;
			}		
		}
		
		function add(){
			return $this->db->insert($this->tableName, array('CAF_ID' => $this->CAF_ID,
																'CAF_E_S_DATE' => $this->CAF_E_S_DATE,
																'CAF_E_E_DATE' => $this->CAF_E_E_DATE,
																'CAF_E_DAY_REMAIN' => $this->CAF_E_DAY_REMAIN,	
																'PAK_ID' => $this->PAK_ID));
		}
		function edit($cafe_id){
			$data = array();
			
			if (!empty($this->CAF_ID))
				$data['CAF_ID'] = $this->CAF_ID;
			if (!empty($this->CAF_E_S_DATE))
				$data['CAF_E_S_DATE'] = $this->CAF_E_S_DATE;
			if (!empty($this->CAF_E_E_DATE))
				$data['CAF_E_E_DATE'] = $this->CAF_E_E_DATE;
			if (!empty($this->CAF_E_DAY_REMAIN))
				$data['CAF_E_DAY_REMAIN'] = $this->CAF_E_DAY_REMAIN;
			if (!empty($this->PAK_ID))
				$data['PAK_ID'] = $this->PAK_ID;
			
			return $this->db->update($this->tableName, $data);
		}
	}
?>